package com.emapp.lccode.http

import android.content.Intent
import android.util.Log
import com.emapp.lccode.activity.LoginKtActivity
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.ApiResponse
import com.emapp.lccode.utils.MmkvUtil
import com.google.gson.Gson
import com.hjq.toast.Toaster
import me.hgj.jetpackmvvm.base.appContext
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import java.io.IOException

/**
 * 描述　: token过期拦截器
 */
class TokenOutInterceptor : Interceptor {

    val gson: Gson by lazy { Gson() }

    @kotlin.jvm.Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request=chain.request()
        val response = chain.proceed(request)
        return if (response.body != null && response.body!!.contentType() != null) {
            val mediaType = response.body!!.contentType()
            val string = response.body!!.string()
            val responseBody = ResponseBody.create(mediaType, string)
            if (mediaType.toString().contains("image")){
           // if (string.isEmpty() || !string.startsWith("{")) {
                Log.e("TAG", "intercept:11111111111111=image " )
                return  chain.proceed(request)
            }else {
                try {
                    val apiResponse = gson.fromJson(string, ApiResponse::class.java)
                    //判断逻辑 模拟一下
                    when(apiResponse.code){
                        401->{
                            MmkvUtil.putBoolean("isAutoLogin", false)
                            //如果是普通的activity话 可以直接跳转，如果是navigation中的fragment，可以发送通知跳转
//                            appContext.startActivity(
//                                Intent(
//                                    appContext,
//                                    LoginKtActivity::class.java
//                                ).apply {
//                                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
//                                })
                            EventBus.getDefault().post(EventBusModel(EventBusConfig.FINISH))
                            response.close()
                        }
                        404 ->{
                            Log.e("TokenOutInterceptor", "intercept: "+404 )
                        }
                    }
                } catch (e: Exception) {
                    Toaster.show(e.message)
                }
            }
            // 对返回code统一拦截
//            Log.e("TAG", "intercept: 333333333333333333333333333333333")
//            if (response != null) {
//                Log.e("TAG", "intercept: 444444444444444444444444444444444444  "+response.code+response.message)
//                if (response.code == 401) { //
//                    Log.e("TAG", "intercept: 55555555555555555555555555555555")
//                    Toaster.show("登录令牌已过期，请重新登录");
////                    val intent = Intent()
////                    intent.action = "TOKEN_ERROR"
////                    appContext.sendBroadcast(intent)
//                    appContext.startActivity(Intent(appContext, LoginActivity::class.java).apply {
//                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
//                    })
//                }
//                response.close()
//            }
            //chain.proceed(request) //这里会导致调用两次打印日志
            response.newBuilder().body(responseBody).build()

        } else {
            response
        }
    }
}